#! python3.8.5

"""
应随机生成5000个以上的联系人进行测试，对排序输出，查找等的效率进行观察。
"""

from datetime import datetime as dt
from random import randint

from AddressBook import AddressBook
from Head import Head

if __name__ == '__main__':

    with open("Data.txt", "r", encoding="utf-8") as f:
        lines = f.read().split("\n")
    data = [line.split("\t") for line in lines]
    ab = AddressBook()
    for d in data:
        ab.add(d[0], d[1], d[2], Head(d[3], 200, 200))
    n = ab.get_records_num()
    print("数据导入完成。")


    def tm_search(attr, k, num):
        x = [randint(0, n) for i in range(num)]
        result = []
        for i in x:
            t1 = dt.now()
            ab.search(attr, data[i][k])
            t2 = dt.now()
            result.append((t2 - t1).microseconds)
        with open("tm_result.txt", "a", encoding="utf8") as f:
            f.write(f"{attr}属性搜索测试：\n")
            f.write(f"测试次数：{num}\n")
            f.write(f"平均时间：{sum(result) / 100000}ms\n\n")


    with open("tm_result.txt", "a", encoding="utf8") as f:
        f.write(f"通讯簿规模：{n}\n\n")
        f.write("\n搜索效率测试：\n\n")

    print("搜索时间效率测试开始。")
    tm_search("name", 0, 100)
    tm_search("tel", 1, 100)
    tm_search("email", 2, 100)
    print("搜索时间效率测试结束。")


    def tm_show():
        rule_list = ["default", "name", "tel", "email", "pinyin"]
        for rule in rule_list:
            # 正序测试
            t1 = dt.now()
            ab.show(rule)
            t2 = dt.now()
            t = (t2 - t1).microseconds
            # 倒序测试
            t3 = dt.now()
            ab.show(rule, reverse=True)
            t4 = dt.now()
            r = (t4 - t3).microseconds
            with open("tm_result.txt", "a", encoding="utf8") as f:
                f.write(f"排序依据：{rule}\n")
                f.write(f"正序花费时间：{t / 1000}ms\n")
                f.write(f"倒序花费时间：{r / 1000}ms\n\n")


    with open("tm_result.txt", "a", encoding="utf8") as f:
        f.write("\n\n排序输出测试：\n\n")

    print("输出时间效率测试开始。")
    tm_show()
    print("搜索时间效率测试结束。")
